package org.cainiao.basic.concurrent.juc.aqs.countdownlatch;

import org.cainiao.util.Util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class CountDownLatchRunnable implements Runnable {

    private final String name;
    private final int seconds;
    private final CountDownLatch countDownLatch;

    @Override
    public void run() {
        Util.logLn("%s start", name);
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            Util.logLn("%s countDownLatch before countDown", name);
            countDownLatch.countDown();
        }
    }

    public static Thread newThread(String name, int seconds, CountDownLatch semaphore) {
        return new Thread(new CountDownLatchRunnable(name, seconds, semaphore));
    }

    private CountDownLatchRunnable(String name, int seconds, CountDownLatch countDownLatch) {
        this.name = name;
        this.seconds = seconds;
        this.countDownLatch = countDownLatch;
    }
}
